function [ data, dataIdx ] = readCellContours( fileDir, measNum, maxContourNum )
% samplename = 'Sample';
% fileDir = [rootdir filesep samplename filesep 'Online' filesep];
file = dir([fileDir sprintf('M%i_*contours.txt', measNum)]);

[~, result] = system( ['wc -l ', [fileDir file.name]] );
spaceIdx = strfind(result,' ');
numLines = str2num( result(1:spaceIdx(1)-1) );

fid = fopen([fileDir file.name],'r');

strKeyFrame = 'Contour in frame';
data = zeros(numLines,2);
dataIdx = zeros(maxContourNum, 3);
dataPtr = 1;
dataIdxPtr = 1;

while ~feof(fid)
    frame = getFrame(fid, strKeyFrame);
    dataCell = getDataSet(fid);
    dataCellLength = length(dataCell(:,1));
    data(dataPtr:dataPtr+dataCellLength-1,:) = dataCell;
    dataIdx(dataIdxPtr,:) = [frame dataPtr dataCellLength];
    
    dataPtr=dataPtr+dataCellLength;
    dataIdxPtr = dataIdxPtr + 1;
end
data(sum(data,2) == 0,:) = [];
dataIdx(sum(dataIdx,2) == 0,:) = [];
fclose(fid);
end

function frame = getFrame(fid, strKeyFrame)
while ~feof(fid)
    strLine = fgets(fid);
    index = strfind(strLine, strKeyFrame);
    if ~isempty(index)
        frame = str2double(strLine(index + length(strKeyFrame):end));
        return;
    end
end
end

function data = getDataSet(fid)
c = textscan(fid,'( %u , %u )');
data = [c{1} c{2}];

% mask = (data <= 0) | (data >= 250);
% mask = mask(:,1) | mask(:,2);
% startIdx = find(mask, 1, 'first');
% data(startIdx:end,:) = [];
% 
% if (sum((double(data(end-1,:))-double(data(1,:))).^2) < sum((double(data(end-1,:))-double(data(end,:))).^2)) || ...
%         (sum((double(data(end-1,:))-double(data(1,:))).^2) < sum((double(data(end,:))-double(data(1,:))).^2))
%     data(end,:) = [];
% end
end





